# -*- coding: utf-8 -*-
"""全局变量管理模块

提供跨模块共享的全局变量存取功能。

@Time    : 2021/11/20 11:51
@Author  : 徐良
@File    : globalvar.py
"""

from typing import Any

_global_dict = {}

def init() -> None:
    """初始化全局变量字典（可选手动调用）"""
    # global _global_dict
    # _global_dict = {}
    pass

def set_value(name: str, value: Any) -> None:
    """设置全局变量的值

    Args:
        name: 变量名称
        value: 变量值
    """
    _ensure_initialized()
    _global_dict[name] = value

def get_value(name: str, def_value: Any = None) -> Any:
    """获取全局变量的值

    Args:
        name: 变量名称
        def_value: 默认值（当变量不存在时返回）

    Returns:
        Any: 对应变量值或默认值
    """
    _ensure_initialized()
    return _global_dict.get(name, def_value)

def _ensure_initialized() -> None:
    """确保全局变量已初始化"""
    global _global_dict
    if '_global_dict' not in globals() or not isinstance(_global_dict, dict):
        _global_dict = {}

def exists(name: str) -> bool:
    """检查变量是否已存在

    Args:
        name: 变量名称

    Returns:
        bool: 存在返回 True，否则 False
    """
    _ensure_initialized()
    return name in _global_dict


